package com.jzy.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzy.common.constant.WareConstant;
import com.jzy.common.utils.PageUtils;
import com.jzy.common.utils.Query;
import com.jzy.gulimall.ware.dao.PurchaseDao;
import com.jzy.gulimall.ware.entity.PurchaseDetailEntity;
import com.jzy.gulimall.ware.entity.PurchaseEntity;
import com.jzy.gulimall.ware.service.PurchaseDetailService;
import com.jzy.gulimall.ware.service.PurchaseService;
import com.jzy.gulimall.ware.service.WareSkuService;
import com.jzy.gulimall.ware.vo.MergeVo;
import com.jzy.gulimall.ware.vo.PurchaseDoneVo;
import com.jzy.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Resource
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 采购单维护 采购需求 合并到整单 采购单列表
     * ware/purchase/unreceive/list
     */
    @Override
    public List<PurchaseEntity> unreceiveList() {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);
        return this.list(wrapper);
    }

    /**
     * 采购单维护 合并整单 合并
     * ware/purchase/merge  {"purchaseId":2,"items":[1,2]}
     */
    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        if (purchaseId == null) {
            //新建采购单
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setPriority(0);
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREAT.getCode());
        } else {
            purchaseEntity.setId(purchaseId);
            // TODO: 2020/9/9 确认采购单是0或者1 采购需求是0或者1 才可以合并
        }
        //采购单更新时间
        purchaseEntity.setUpdateTime(new Date());
        this.saveOrUpdate(purchaseEntity);
        purchaseId = purchaseEntity.getId();
        //合并采购单
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = mergeVo.getItems().stream().map(id -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(id);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);
    }

    /**
     * 领取采购单
     * http://localhost:88/api/ware/purchase/received
     * [1,2,3,4] json
     */
    @Override
    @Transactional
    public void receivedPurchase(List<Long> ids) {
        // 1.确认当前采购单 状态
        List<PurchaseEntity> collect = this.listByIds(ids).stream()
                .filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREAT.getCode() ||
                        item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                })
                .collect(Collectors.toList());
        // 2.改变采购单的状态
        this.updateBatchById(collect);
        // 3.改变采购需求的状态
        collect.forEach(item -> {
            //根据采购单Id获取所有采购需求数据
            List<PurchaseDetailEntity> entitys = purchaseDetailService.listPurchaseDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> list = entitys.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(list);
        });
    }

    /**
     * 完成采购单
     * ware/purchase/done
     * {
     * "id": 3,
     * "items": [{"itemId":1,"status":4,"reason":""}]
     * }
     */
    @Override
    @Transactional
    public void donePurchase(PurchaseDoneVo doneVo) {
        //2.改变采购项的状态
        boolean flag = true;
        ArrayList<PurchaseDetailEntity> list = new ArrayList<>();
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
            //是否采购成功
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FAIL.getCode()) {
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.将采购成功的进行入库
                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            list.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(list);
        //1.改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}